<?php
namespace App\Services;

use Config;
use App\Services\Openssl\CustomSearchException;

/**
*
*/
class CustomSearch
{

    protected $config;
    protected $pubkey;

    function __construct()
    {

        $config = config('eorderinfo');
        $this->config = $config;

    }

    /** 设置参数
     * @param $key
     * @param $value
     */
    public function setParam($key,$value){
        $this->params[$key] = $value;
    }



    public function sendPost($goods_sn){

            $xmlorder = '<?xml version="1.0" encoding="utf-8"?>
                        <root>
                            <pub>
                                <request_time>' . date('Y-m-d H:i:s') . '</request_time>
                                <user_code>' . $this->config['ecpCodeCus_new'] . '</user_code>
                                <type>2</type>
                            </pub>
                            <goods>
                                <good_no>' . $goods_sn . '</good_no>
                            </goods>
                        </root>';

       // echo $xmlorder;
        return $this->makeRequest($this->config['customSearch'], ['xml' => $xmlorder]);
    }


    /**
     * 构建请求
     * @param $data
     * @return mixed|string
     */
    private function makeRequest($url, $data)
    {

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            $response = curl_exec($ch);
            // echo $response;exit();


        }catch (\Exception $e){

            throw new CustomSearchException($e->getMessage());
        }

        if ($response) {

            $response = str_replace('&', '&amp;', $response);
        }

        $repsonXmlObj = simplexml_load_string($response);

        if($repsonXmlObj->goods){


            $goods = (json_decode(json_encode($repsonXmlObj->goods),TRUE));

            $goodArray = [];
            foreach($goods as $k=>$v){
                // print_r ($v);
                if (isset($v['good_no'])){
                    $goodArray[$v['good_no']] = $v;

                }
            }

            return $goodArray;
        }
        else{

            throw new CustomSearchException($repsonXmlObj->Detail);
        }



    }


}

?>